package com.piaoniu.open.http;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Here be dragons
 * Created by haotian on 2018/7/7 下午3:20
 */
public class FormEntity extends StringEntity {

    public FormEntity(Map<String,String> params) {

        super(getString(params), ContentType.APPLICATION_FORM_URLENCODED.withCharset("utf-8"));
    }

    private static String getString(Map<String,String> params) {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(params.size());
        for (Map.Entry<String, String> entry : params.entrySet()) {
            nameValuePairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
        }
        return URLEncodedUtils.format(nameValuePairs, "utf-8");

    }

    public static FormEntity from(Map<String,String>  params) {
        return new FormEntity(params);
    }
}
